package com.dragon.executor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 进程代理执行器。
 * 职责：安全地启动一个子进程，并完整地转发所有 I/O 流。
 * 它不关心子进程具体做什么，只做可靠的“管道工”。
 */
@Deprecated
public class CodeExecutor {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("用法: CodeExecutor <真正的main类> [参数...]");
            System.exit(1);
        }

        Process subProcess = null;
        try {
            List<String> command = new ArrayList<>();
            command.add("java");
            command.add("-cp");
            command.add(System.getProperty("java.class.path"));
            command.addAll(Arrays.asList(args)); // 将所有参数传递给子进程

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            subProcess = processBuilder.start();

            // 转发 I/O 流
            Thread inputForwarder = new Thread(new StreamForwarder(System.in, subProcess.getOutputStream()));
            Thread outputForwarder = new Thread(new StreamForwarder(subProcess.getInputStream(), System.out));
            Thread errorForwarder = new Thread(new StreamForwarder(subProcess.getErrorStream(), System.err));

            inputForwarder.start();
            outputForwarder.start();
            errorForwarder.start();

            int exitCode = subProcess.waitFor();

            inputForwarder.join();
            outputForwarder.join();
            errorForwarder.join();

            System.exit(exitCode);

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            if (subProcess != null) {
                subProcess.destroyForcibly();
            }
        }
    }

    // StreamForwarder 保持不变
    static class StreamForwarder implements Runnable {
        private final InputStream in;
        private final OutputStream out;

        StreamForwarder(InputStream in, OutputStream out) {
            this.in = in;
            this.out = out;
        }

        @Override
        public void run() {
            try {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                    out.flush();
                }
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}